<template>
	<view :class="{'container':true,'verflow': open}">
		<view class="addTitle">
			<view class="titleDetail">
				<view class="titleLeft">
					<image src="../../static/newh5/fanhui.png" class="yticon"
						style="width: 13px;height: 20px;color:black" @click="returnIndex()"></image>
				</view>
				<view class="titleCenter">
					<b class="titleText">浏览历史({{totalNum}})</b>


				</view>
				<view class="titleRight">
					<text class="right-btn"  @click="open=true">筛选</text>
					<text class="right-btn" @click="isSelect=!isSelect">{{!isSelect?'管理':'完成'}}</text>
				</view>
			</view>


		</view>
		<view :class="{'goods-wrap':isSelect}">
			<template v-if="historyList&&historyList.length>0">
				<view class="goods-time" v-for="(item,index) in historyList" :key="index">
					<view class="cur-time">
						<template v-if="isSelect">
							<image @click="selectGood(false,index,undefined)" v-if="item.select" class="select-icon"
								src="../../static/selected.png" mode="aspectFill">
							</image>
							<image @click="selectGood(true,index,undefined)" v-else class="select-icon"
								src="../../static/select.png" mode="aspectFill"></image>
						</template>
						<text>{{item.modifyTime}}</text>

					</view>
					<view class="goods-box-single" v-for="(good,num) in item.subList" :key="num">
						<template v-if="isSelect">
							<image @click="selectGood(false,index,num)" v-if="good.select" class="select-icon"
								src="../../static/selected.png" mode="aspectFill">
							</image>
							<image @click="selectGood(true,index,num)" v-else class="select-icon"
								src="../../static/select.png" mode="aspectFill"></image>
						</template>
						<view class="img-wrapper">
							<image class="goods-img" :src="good.goodsImage" mode="aspectFill"></image>
							<image v-if="good.goodsStatus == 2" class="tag" src="../../static/undercarriage.png"/>
							<image v-if="good.goodsStatus == 3" class="tag" src="../../static/failure.png"/>
						</view>
						<view class="right">
							<text class="title more-t">{{good.goodsName}}</text>
							<text class="price">{{good.goodsPrice}}</text>
						</view>
						<image @click="addCart(good)" class="cart-icon" src="../../static/cart.png" mode="widthFix"></image>
					</view>
				</view>
			</template>
			<u-empty v-else text="暂无数据" style="padding-top: 100rpx;"></u-empty>
		</view>
		<view :class="{'action-section':true,show:isSelect}">
			<view class="checkbox">
				<view @click="allCheckedClick">
					<image :src="allChecked?'/static/selected.png':'/static/select.png'" mode="aspectFit"></image>
					<text>全选</text>
				</view>
				<view>
					<view class="del-btn" @click="del">
						删除
					</view>
				</view>

			</view>
		</view>
		<l-popup title="浏览时间" showReset :open.sync="open" round="20" @reset="handleReset" @confirm="handleConfirm" @cancel="handleCancel">
			<view class="popup-content">
				<view class="popup-top">
					<view :class="{'day':true,'isActive':curDay == 3}" @click="changeRecent('3')">
						近3天
					</view>
					<view class="day" :class="{'day':true,'isActive':curDay == 7}" @click="changeRecent('7')">
						近7天
					</view>
					<view class="day" :class="{'day':true,'isActive':curDay == 10}" @click="changeRecent('10')">
						近10天
					</view>
				</view>
				<view class="dateContent" @click="onShowDatePicker()">
					<view class="dateContent-item">
						<text style="color:#c2c3c5 ;" v-if="!dateValue.length">开始时间</text>
						<text v-else>{{dateValue[0].slice(0,10)}}</text>
					</view>
					<span>~</span>
					<view class="dateContent-item">
						<text style="color:#c2c3c5 ;" v-if="!dateValue.length">结束时间</text>
						<text v-else>{{dateValue[1].slice(0,10)}}</text>
					</view>
				</view>

			</view>
		</l-popup>
		<mx-date-picker :show="showPicker" :color="color" :type="dateType" :value="dateValue" :show-tips="true"
			:show-seconds="true" @confirm="onSelected" @cancel="onSelected" />
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	import {
	  addToCart
	} from '@/api/cart/cart.js'
	import
	lPopup
	from "@/components/l-popup/l-popup.vue";
	import {
		goback
	} from "@/common/utils/navigateBack.js";
	import {
		goodsViewHistoryList,
		goodsViewHistoryDeleteList
	} from '../../api/history/history.js'
	import MxDatePicker from "@/components/mx-datepicker/mx-datepicker.vue";

	import moment from 'moment';
	export default {
		components: {
			lPopup,
			MxDatePicker
		},
		data() {
			return {
				isSelect: false,
				historyList: [],
				allChecked: false,
				open: false,
				showPicker: false,
				color: 'rgba(34, 34, 34, 1)',
				dateType: 'rangetime',
				dateValue: [],
				startTime: '',
				endTime: '',
				curDay:'',
				totalNum: 0
			}
		},
		computed: {
			...mapState(['hasLogin'])
		},
		onLoad(op) {},
		mounted() {
			this.loadData('refuse')
		},
		methods: {
			onSelected(e, key) { //选择
				this.showPicker = false;
				this.curDay=''
				if (e) {
					this.dateValue = e.value;
					if (e.value && e.value.length) {
						let item = this.item;
						this.dateValue[0] = e.value[0].replaceAll('/', '-');
						this.startTime = e.value[0].replaceAll('/', '-');
						this.dateValue[1] = e.value[1].replaceAll('/', '-');
						this.endTime = e.value[1].replaceAll('/', '-');
					}
					//选择的值
					console.log('startTime => ' + this.startTime);
					console.log('endTime => ' + this.endTime);
				}
			},

			onShowDatePicker(key, item) { //显示
				this.showPicker = true;
			},
			handleConfirm() {
				if(!this.curDay&&(!this.dateValue||this.dateValue.length===0))
				this.loadData('refuse')
				else
				this.loadData()
			},
			handleReset(){
				this.curDay=''
				this.dateValue = []
			},
			handleCancel() {

			},
			returnIndex() {
				goback()
			},
			getStartTime() {
				const date = new Date()
				const year = date.getFullYear()
				const month = date.getMonth() + 1
				const day = date.getDate()

				const date1 = new Date(date - 1000 * 60 * 60 * 24 * 30)
				const year1 = date1.getFullYear()
				const month1 = date1.getMonth() + 1
				const day1 = date1.getDate()
				this.startTime = year1 + "-" + (month1 < 10 ? "0" + month1 : month1) + "-" + (day1 < 10 ? "0" + day1 :
					day1) + ' 00:00:00' // 30天前的日期
				this.endTime = `${year}-${month+1}-${day}` + ' 23:59:59' // 当天的日期
			},
			changeRecent(value) {
				this.curDay=value
				console.log(value,new Date().getTime());
				// 开始日期
				this.endTime = moment(new Date()).format('YYYY-MM-DD') + ' ' + '23:59:59';
				let end = new Date().getTime() - value * 1000 * 24 * 60 * 60;
				this.startTime = moment(end).format('YYYY-MM-DD') + ' ' + '00:00:00';
				this.dateValue = [this.startTime,this.endTime]
				// 结束日期  value 3、7、10

		},

		selectGood(type, index, num) {
			if (num == undefined) {
				this.$set(this.historyList[index], 'select', type)
				let good = this.historyList[index].subList.map(item => {
					return {
						...item,
						select: type
					}
				})
				this.$set(this.historyList[index], 'subList', good)
			} else {
				this.$set(this.historyList[index]['subList'][num], 'select', type)
				this.$set(this.historyList[index], 'select', type)
			}

		},
		allCheckedClick() {
			this.allChecked = !this.allChecked
			// if(this.allChecked) {
			for (let i = 0; i < this.historyList.length; i++) {
				this.$set(this.historyList[i], 'select', this.allChecked)
				for (let j = 0; j < this.historyList[i].subList.length; j++) {
					this.$set(this.historyList[i]['subList'][j], 'select', this.allChecked)
				}
			}
			// }
		},
		del() {
			let params = {
				idList: []
			}
			for (let i = 0; i < this.historyList.length; i++) {

				for (let j = 0; j < this.historyList[i].subList.length; j++) {
					let good = this.historyList[i]['subList'][j]
					if (good.select == true) {
						params.idList.push(good.goodsId)
					}
				}
			}
			if (params.idList.length == 0) {
				this.$util.msg('请选择要删除的历史记录')
				return false
			}
			goodsViewHistoryDeleteList(params).then(res => {
				if (res.code == 0) {
					this.$util.msg('删除成功')
					this.loadData('refuse')
				}
			})
		},
		loadData(type) {
			if (type == 'refuse') {
				this.getStartTime()
			}
			let param = {
				page: 1,
				limit: 500,
				endTime: this.endTime,
				startTime: this.startTime
			}
			goodsViewHistoryList(param).then(res => {
				if (res.code == 0) {
					let newArr = [];
					this.totalNum = res.data.total
					if(!res.data.records.length) {
						this.historyList = newArr
						return false
					}
					//通过forEach循环数组
					res.data.records.forEach((item, i) => {
						let index = -1;
						//然后在跑到这里筛选 根据不同的时间放置不同的数组    some（）用来查找数组中是否存在某个值  如果存在 就return true
						let isExists = newArr.some((newItem, j) => {

							if (item.modifyTime.slice(0, 10) == newItem.modifyTime.slice(0,
									10)) {
								index = j;
								return true;
							}
						})
						//代码是先跑这里的if条件判读  
						if (!isExists) {
							newArr.push({
								modifyTime: item.modifyTime.slice(0, 10),
								subList: [item]
							})
						} else {
							newArr[index].subList.push(item);
						}
						this.historyList = newArr
					})
				}
			})
		},
		addCart(item) {
			if (!this.hasLogin) {
				uni.showModal({
					title: '提示',
					content: '您还未登录，不能进行此操作',
					confirmText: '去登录',
					cancelText: '取消',
					success: (suc) => {
						if (suc.confirm) {
							uni.navigateTo({
								url: '/pages/public/login'
							})
						}
					}
				})
			} else {
				let pType;
				let qType;
				if (item.goodsSourceType === 0) {
					pType = '02';
					qType = 1;
				} else {
					pType = '01';
					qType = 2;
				}
				const good = {
					protocolGoodsId: item.goodsId,
					protocolId: item.protocolId,
					protocolType: pType,
					remainAmount: 1
				}
				const params = {
					areaId: uni.getStorageSync('areaId'),
					goodsId: item.goodsId,
					num: 1
				}
				addToCart(params).then(res => {
					if (res.code === 0) {
						this.$util.msg('加入购物车成功')
					} else if(res.code === 1001) {
						let msg = ''
						if(res.extra.productAvailability) {
							msg = res.extra.productAvailability.filter(item => !item.canPurchase).map(item => item.message).toString()
						}
						this.$util.msg(res.message+' '+msg)
					}else {
						this.$util.msg(res.message)
					}
				})
			}
		}
	}
	}
</script>

<style lang='scss'>
	page {
		background-color: #fff;
	}
	.verflow {
		height: 100%;
		overflow: hidden;
	}
	.dateContent {
		&>view {
			background: #f4f4f4;
			border-radius: 8upx;
			width: 260upx;
			height: 70upx;
			line-height: 70upx;
			margin-bottom: 12upx;
			padding: 0 12upx;
			display: inline-block;
			margin-top: 30upx;

		}

		&>text {
			margin: 0 20upx;
		}

	}

	.popup-content {
		.popup-top {
			.day {
				display: inline-block;
				padding: 15upx 34upx;
				background-color: #f2f2f2;
				color: #c2c3c5;
				font-size: 30upx;
				margin-right: 46upx;
				border-radius: 40upx;
				margin-top: 44upx;
				&.isActive {
					background-color: #fa541c;
					color: #fff;
				}
			}
		}
	}

	.addTitle {
		position: sticky;
		left: 0;
		top: 0;
		z-index: 9999;
		width: 100%;
		height: 100rpx;
		text-align: center;
		display: flex;
		flex-direction: column;
		background-color: rgba($color: #f5f5f5, $alpha: 0.8);

		.titleDetail {
			display: flex;
			align-items: center;
			padding: 10rpx;
			height: 44px;
			justify-content: space-between;
			background-color: white;

			.titleLeft {
				flex: 1;
				text-align: left
			}

			.titleCenter {
				display: flex;
				flex: 1;
				// text-align:left
			}

			.titleRight {
				flex: 1;
				text-align: right
			}

			.right-btn {
				margin-right: 20upx;
			}

			.titleText {
				font-size: 16px;
				opacity: 1;
			}
		}
	}

	.select-icon {
		width: 50upx;
		height: 50upx;
		vertical-align: middle;
		margin-right: 20upx;
	}

	.cur-time {
		font-size: 36upx;
		font-weight: bold;
		background-color: #fff;
		text-align: left;
		padding: 20upx 20upx
	}

	.goods-wrap {
		height: calc(100vh - 226upx);
		overflow: hidden;
		overflow-y: auto;
	}

	/* 单条商品 */
	.goods-box-single {
		display: flex;
		padding: 20upx;
		align-items: center;
		background-color: #fff;

		.cart-icon {
			width: 74upx;
			/* height: 66upx; */
		}
		
		.img-wrapper{
			position: relative;
			.goods-img {
				display: block;
				width: 160upx;
				height: 160upx;
				border-radius: 6upx;
				background-color: #fff;
				background: url(../../static/error-img-60.png);
			}
			.tag{
				position: absolute;
				width: 120rpx;
				height: 120rpx;
				left: 20rpx;
				top: 20rpx;
			}
		}

		.right {
			flex: 1;
			height: 160upx;
			display: flex;
			flex-direction: column;
			padding: 0 30upx 0 24upx;
			overflow: hidden;
			text-align: left;
			justify-content: space-around;

			.title {
				font-size: $font-base;
				color: $font-color-dark;
				line-height: 42rpx;
			}

			.attr-box {
				font-size: $font-sm + 2upx;
				color: $font-color-light;
				padding: 10upx
			}

			.price {
				font-size: $font-base + 2upx;
				color: $uni-color-primary;

				&:before {
					content: '￥';
					font-size: $font-sm;
					margin: 0 2upx 0 8upx;
				}
			}
		}
	}

	/* 底部栏 */
	.action-section {
		/* #ifdef H5 */
		margin-bottom: var(--window-bottom);
		/* #endif */
		position: fixed;
		left: 20upx;
		right: 20rpx;
		bottom: 20upx;
		z-index: 90005;
		display: none;
		/* width: 690upx; */
		min-height: 76upx;
		padding: 0 20upx;
		background: rgba(255, 255, 255, .9);
		box-shadow: 0 0 20upx 0 rgba(0, 0, 0, .5);
		border-radius: 16upx;

		&.show {
			display: block;
		}

		&.BT20 {
			bottom: 60upx;
		}

		.total-box-left {
			flex: 1;
			/* line-height: 80upx; */
		}

		.checkbox {
			/* min-height: 52rpx; */
			height: fit-content;
			/* position: relative; */
			text-align: left;
			margin-top: 16upx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			text {
				vertical-align: middle;
			}

			image {
				width: 42upx;
				height: 42rpx;
				/* position: relative; */
				z-index: 5;
				margin-right: 10upx;
				vertical-align: middle;
			}
		}

		.clear-btn {
			/* position: absolute; */
			margin-left: -26upx;
			top: 0;
			z-index: 4;
			width: 0;
			display: flex;
			align-items: center;
			height: 0;
			/* line-height: 52upx; */
			padding-left: 36upx;
			padding-right: 20rpx;
			font-size: $font-base;
			color: #fff;
			background: $font-color-disabled;
			border-radius: 0 50px 50px 0;
			opacity: 0;
			transition: .2s;

			&.show {
				opacity: 1;
				width: fit-content;
				min-height: 52rpx;
				height: fit-content;
			}
		}

		.del-btn {
			border: 1px solid #84878e;
			padding: 4upx 22upx;
			border-radius: 34upx;
		}

		.total-box {
			flex: 1;
			display: flex;
			/*flex-direction: column;*/
			justify-content: space-between;
			align-items: center;
			/* padding-left: 60upx; */
			/* line-height: 40upx; */

			.price {
				font-size: $font-base + 4upx;
				color: $uni-color-primary;
			}

			.split {
				font-size: $my-font-size-base;
				color: $base-color;
			}

			.coupon {
				font-size: $font-sm;
				color: $font-color-light;

				text {
					color: $uni-color-primary;
				}
			}
		}

		.confirm-btn {
			padding: 0 38upx;
			margin: 0;
			border-radius: 100px;
			line-height: normal;
			height: 76upx;
			display: flex;
			align-items: center;
			justify-content: center;
			/* line-height: 76upx; */
			/* text-align: right; */
			font-size: $font-base + 2upx;
			background: $uni-color-primary;
			/* vertical-align: middle; */
			box-shadow: 1px 2px 5px rgba(217, 60, 93, 0.72)
		}
	}
</style>
